package net.net23.sysdent.server.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class SignFilter implements Filter {

	private static final Logger log = Logger.getLogger(SignFilter.class
			.getName());

	private ArrayList<String> urlList;
	private int totalURLS;

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		String url = request.getServletPath();
		boolean allowedRequest = false;

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		if (user == null) {
			for (int i = 0; i < totalURLS; i++) {
				if (url.matches(urlList.get(i))) {
					allowedRequest = true;
					break;
				}
			}
			if (!allowedRequest) {
				String loginUrl = userService.createLoginURL(request
						.getRequestURI());
				log.log(Level.SEVERE, loginUrl);
				response.sendRedirect(loginUrl);
				return;
			}

		}
		chain.doFilter(req, resp);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String urls = config.getInitParameter("avoid-urls");
		StringTokenizer token = new StringTokenizer(urls, ",");

		urlList = new ArrayList<String>();

		while (token.hasMoreTokens()) {
			urlList.add(token.nextToken());

		}
		totalURLS = urlList.size();
	}
}
